package com.yix.admin.modules.system.service.impl;

import com.yix.admin.modules.system.entity.SysJob;
import com.yix.admin.modules.system.entity.dto.SysJobDto;
import com.yix.admin.modules.system.entity.mapper.SysJobMapper;
import com.yix.admin.modules.system.entity.query.SysJobQuery;
import com.yix.admin.modules.system.repository.SysJobRepository;
import com.yix.admin.modules.system.repository.SysUserRepository;
import com.yix.admin.modules.system.service.SysJobService;
import com.yix.common.exception.BadRequestException;
import com.yix.common.exception.EntityExistException;
import com.yix.common.utils.*;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @author wdx
 * @version 1.0
 * @Description TODO
 * @date 2021/2/7 17:05
 */
@Service
@CacheConfig(cacheNames = "job")
public class SysJobServiceImpl implements SysJobService {

    @Autowired
    private SysJobRepository sysJobRepository;
    @Autowired
    private SysUserRepository sysUserRepository;
    @Autowired
    private SysJobMapper sysJobMapper;
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public Map<String,Object> queryAll(SysJobQuery criteria, Pageable pageable) {
        Page<SysJob> page = sysJobRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(sysJobMapper::toDto).getContent(),page.getTotalElements());
    }

    @Override
    public List<SysJobDto> queryAll(SysJobQuery criteria) {
        List<SysJob> list = sysJobRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder));
        return sysJobMapper.toDto(list);
    }

    @Override
    @Cacheable(key = "'id:' + #p0")
    public SysJobDto findById(String id) {
        SysJob job = sysJobRepository.findById(id).orElseGet(SysJob::new);
        ValidationUtil.isNull(job.getId(),"Job","id",id);
        return sysJobMapper.toDto(job);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(SysJob resources) {
        SysJob job = sysJobRepository.findByName(resources.getName());
        if(job != null){
            throw new EntityExistException(SysJob.class,"name",resources.getName());
        }
        sysJobRepository.save(resources);
    }

    @Override
    @CacheEvict(key = "'id:' + #p0.id")
    @Transactional(rollbackFor = Exception.class)
    public void update(SysJob resources) {
        SysJob job = sysJobRepository.findById(resources.getId()).orElseGet(SysJob::new);
        SysJob old = sysJobRepository.findByName(resources.getName());
        if(old != null && !old.getId().equals(resources.getId())){
            throw new EntityExistException(SysJob.class,"name",resources.getName());
        }
        ValidationUtil.isNull( job.getId(),"Job","id",resources.getId());
        resources.setId(job.getId());
        sysJobRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Set<String> ids) {
        sysJobRepository.deleteAllByIdIn(ids);
        // 删除缓存
        redisUtils.delByKeys(CacheKey.JOB_ID, ids);
    }

    @Override
    public void download(List<SysJobDto> jobDtos, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (SysJobDto jobDTO : jobDtos) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("岗位名称", jobDTO.getName());
            map.put("岗位状态", jobDTO.getEnabled() ? "启用" : "停用");
            map.put("创建日期", jobDTO.getCreateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public void verification(Set<String> ids) {
        if(sysUserRepository.countByJobs(ids) > 0){
            throw new BadRequestException("所选的岗位中存在用户关联，请解除关联再试！");
        }
    }
}
